package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.dao.RoleDao;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
     private RoleDao roleDao;

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    //根据userids查询对应的roleIds
    public List<Integer> findUserIdByroleids(Integer id) {
        List<Integer> list = roleDao.findUserIdByroleids(id);
        return list;
    }
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        //分页
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page = roleDao.findAllRole(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    public void add(Role role, Integer[] permissions, Integer[] menus) {
        //添加角色
        roleDao.addRole(role);
        //批量设置角色和权限、菜单的关联关系
        Integer roleId = role.getId();
        if (permissions.length > 0) {
            setRoleAndPermission(roleId,permissions);
        }
        if (menus.length > 0) {
            setRoleAndMenu(roleId,menus);
        }
    }

    /**
     * 删除角色
     * @param id
     */
    public void delete(Integer id) {
        //删除与权限的关联关系
        roleDao.deleteAndPermission(id);
        //删除与菜单的关联关系
        roleDao.deleteAndMenu(id);
        //删除角色
        roleDao.deleteRole(id);
    }

    /**
     * 批量设置角色和权限的关联关系
     */
    public void setRoleAndPermission(Integer roleId, Integer[] permissions){
        roleDao.setRoleAndPermission(roleId,permissions);
    }

    /**
     * 批量设置角色和菜单的关联关系
     */
    public void setRoleAndMenu(Integer roleId,Integer[] menus){
        roleDao.setRoleAndMenu(roleId,menus);
    }
}
